package com.hxc.sercurity.service;

import com.hxc.sercurity.configu.projo.LoginUserDetails;
import com.hxc.sercurity.configu.projo.User;
import com.hxc.sercurity.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 韩先楚
 */
@Service()
@Slf4j
public class MyDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        com.hxc.sercurity.configu.projo.User user = userMapper.GetUserByUsername(s);
//        User user1 = userMapper.GetUserByUsername(s);
//       黑马程序员
//        if (user == null) {
//          log.info("User not found with username: {}" ,s);
//            throw new UsernameNotFoundException("User not found with username: " + s);
//        }
//        //这里设置当前用户的具有的权限 如这个权限是admin
//        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin,ROLE_user");
//        return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),list);
//    }

        //草更木堂
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //先向数据库查询user信息
        User user = userMapper.GetUserByUsername(s);
        if (user == null) {
            log.info("User not found with username: {}", s);
            throw new UsernameNotFoundException("User not found with username: " + s);
        }
        //有这个用户
        //ToDO 权限设置
          user.setPassword(encoder.encode(user.getPassword()));
        //获取数据库中的用户具有的权限
        String role = user.getRole();
        //封装权限信息
        List<String> list = new ArrayList();
        list.add(role);
        return new LoginUserDetails(user,list);

    }
}
